import { hash } from "ohash";
import modal from "@/plugins/modal";

const fetch = (url: string, options?: any): Promise<any> => {
    const requestUrl = useRuntimeConfig().public.API_BASE + url;
    // 不设置key，始终拿到的都是第一个请求的值，参数一样则不会进行第二次请求
    const key = hash(JSON.stringify(options) + "_" + url);
    // 如果需要统一加参数可以options.params.token = 'xxx'
    return new Promise((resolve, reject) => {
        useFetch(requestUrl, { ...options, key })
            .then(({ data, error }) => {
                if (error.value) {
                    modal.msgError("无法连接到服务器");
                    reject(error.value);
                    return;
                }
                const value = data.value;
                if (!value) {
                    modal.msgError(value);
                } else {
                    resolve(value);
                }
            })
            .catch((err: any) => {
                reject(err);
            });
    });
};

export default class Http {
    get = (url: string, params?: any) => {
        return fetch(url, { method: "get", params });
    };

    post = (url: string, body?: any) => {
        return fetch(url, { method: "post", body });
    };

    put = (url: string, body?: any) => {
        return fetch(url, { method: "put", body });
    };

    delete = (url: string, body?: any) => {
        return fetch(url, { method: "delete", body });
    };
}